package com.zjh.admin.sys.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjh.admin.sys.model.RoleEntity;
import com.zjh.admin.sys.service.RoleService;
import com.zjh.common.constants.Common;
import com.zjh.common.dtgrid.model.Pager;
import com.zjh.common.dtgrid.util.ExportUtils;
import com.zjh.common.result.Result;
import com.zjh.common.util.PageUtil;
import com.zjh.core.base.basecontroller.BaseController;
import com.zjh.core.exception.AjaxException;
import com.zjh.core.exception.SystemException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ZWX
 * @Description: 资源controller
 * @date 2018/10/15 23：28
 */
@Controller
@RequestMapping("/role/")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    /**
     * list跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listUI.html")
    public String listUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/sys/role/list";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * ajax分页查询角色信息
     *
     * @param gridPager
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/list.html")
    @ResponseBody
    public Object list(String gridPager, HttpServletResponse response) throws Exception {
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        Map<String, Object> parameters = pager.getParameters();
        parameters.put("fastQueryMap", getFastqueryParameters(pager.getFastQueryParameters()));
        //3、判断是否是导出操作
        if (pager.getIsExport()) {
            if (pager.getExportAllData()) {
                //3.1、导出全部数据
                List<RoleEntity> list = roleService.queryListByPage(parameters);
                ExportUtils.exportAll(response, pager, list);
                return null;
            } else {
                //3.2、导出当前页数据
                ExportUtils.export(response, pager);
                return null;
            }
        } else {
            //设置分页，page里面包含了分页信息
            Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);
            List<RoleEntity> list = roleService.queryListByPage(parameters);
            parameters.clear();
            setPageList(parameters, pager, page, list);
            return parameters;
        }
    }

    /**
     * add跳转
     *
     * @return
     */
    @RequestMapping("addUI.html")
    public String addUI() {
        return Common.BACKGROUND_PATH + "/sys/role/form";
    }


    /**
     * 添加角色
     *
     * @param roleEntity
     * @return
     */
    @RequestMapping("add.html")
    @ResponseBody
    public Object add(RoleEntity roleEntity) {
        Result result = new Result();
        try {
            roleEntity.setCreateTime(new Date(System.currentTimeMillis()));
            roleEntity.setStatus(0);
            int status = roleService.insert(roleEntity);
            if (status > 0) {
                result.success("添加成功");
            } else {
                result.error("添加失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }


    /**
     * edit跳转
     *
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("editUI.html")
    public String editUI(Model model, HttpServletRequest request, Long id) {
        try {
            RoleEntity roleEntity = roleService.findById(id);
            PageUtil page = new PageUtil();
            setPage(request, page);

            model.addAttribute("page", page);
            model.addAttribute("roleEntity", roleEntity);
            return Common.BACKGROUND_PATH + "/sys/role/form";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 修改角色
     *
     * @param roleEntity
     * @return
     */
    @RequestMapping("edit.html")
    @ResponseBody
    public Object update(RoleEntity roleEntity) {
        Result result = new Result();
        try {
            int status = roleService.update(roleEntity);
            if (status > 0) {
                result.success("编辑成功");
            } else {
                result.error("编辑失败");
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }


    /**
     * 删除角色
     *
     * @param ids
     * @return
     */
    @RequestMapping("deleteBatch.html")
    @ResponseBody
    public Object deleteBatch(String ids) {
        Result result = new Result();
        try {
            String[] roleIds = ids.split(",");
            //1、检查该角色下是否有用户，如果有则抛异常，没有则执行后面删除操作
            int userCount = roleService.findRoleUserById(Integer.valueOf(roleIds[0]));
            if (userCount > 0) {
                result.error("该角色已分配用户,请去掉用户角色关联后再删除");
            } else {
                Boolean flag = roleService.deleteRoleById(Long.valueOf(roleIds[0]));
                if (flag) {
                    result.success("删除成功");
                } else {
                    result.error("删除失败");
                }
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 验证角色名称是否存在相同
     *
     * @param roleName
     * @return
     */
    @RequestMapping("withoutAuth/validateRoleName.html")
    @ResponseBody
    public Object validateRoleName(@RequestParam(value = "name") String roleName) {
        try {
            System.out.println(roleName);
            //roleName = new String(roleName.getBytes("iso-8859-1"), "utf-8");
            RoleEntity roleEntity = roleService.findByName(roleName);
            return roleEntity == null;

        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }

    /**
     * 权限页面跳转
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("permissionUI.html")
    public String permissionUI(Model model, HttpServletRequest request, Long id) {
        try {
            RoleEntity roleEntity = roleService.findById(id);
            PageUtil page = new PageUtil();
            setPage(request, page);
            model.addAttribute("page", page);
            model.addAttribute("roleEntity", roleEntity);
            return Common.BACKGROUND_PATH + "/sys/role/permission";
        } catch(Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 权限分配
     * @param roleId
     * @param resourceIds
     * @return
     */
    @RequestMapping("permission.html")
    @ResponseBody
    public Object permission(int roleId, String resourceIds) {
        Result result = new Result();
        try {
            List<Integer> list = new ArrayList<>();
            if(StringUtils.isNotBlank(resourceIds)) {
                for (String id : resourceIds.split(",")) {
                    list.add(Integer.valueOf(id));
                }
            }
            boolean status = roleService.addRolePermBatch(roleId, list);
            if(status) {
                result.success("授权成功");
            } else {
                result.error("授权失败");
            }

        } catch(Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

}
